package com.zipking.cloud.springbootmybatis.current;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class MessageQueueSystem {
    private final BlockingQueue<Message> messageQueue = new LinkedBlockingQueue<>();

    public void produceMessage(String content) throws InterruptedException {
        // 将消息添加到队列中，如果队列满了，生产者线程将被阻塞
        messageQueue.put(new Message(content));
        System.out.println("Message produced: " + content);
    }

    public Message consumeMessage() throws InterruptedException {
        // 从队列中取出消息，如果队列空了，消费者线程将被阻塞
        Message message = messageQueue.take();
        System.out.println("Message consumed: " + message.getContent());
        return message;
    }

    public static void main(String[] args) throws InterruptedException {
        MessageQueueSystem messageQueueSystem = new MessageQueueSystem();

        // 创建生产者线程
        Thread producerThread = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    messageQueueSystem.produceMessage("Message " + i);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        // 创建消费者线程
        Thread consumerThread = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    messageQueueSystem.consumeMessage();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producerThread.start();
        consumerThread.start();

        producerThread.join();
        consumerThread.join();
    }
}

class Message {
    private final String content;

    public Message(String content) {
        this.content = content;
    }

    public String getContent() {
        return content;
    }
}

